#!/bin/python3

from pynput.mouse import Listener
from pynput.mouse import Button, Controller
import win32gui, win32ui, win32con, win32api
import csv

recode = []

def _do_stc(x, y):
    hwnd = win32gui.GetForegroundWindow()
    title = ""
    title = win32gui.GetWindowText(hwnd)

    if hwnd:
      cx, cy =  win32gui.ScreenToClient(hwnd, (x, y))
    else:
      cx, cy = x, y
    return title, cx, cy



def on_move(x, y):
    title, rx, ry = _do_stc(x, y)
    # _do_stc(x, y)
    # print("%d %d %d, %d" %(x, y, cx, cy))
    recode.append([title, rx, ry, x, y , "move"])
def check_down(recode):
    index = 0
    for i, row in enumerate(reversed(recode)):
        print(row)
        if row[5] == 'down':
          index = i
          break;
    return -1 - index
      
def on_click(x, y, button, pressed):
    title, rx, ry = _do_stc(x, y)
    print(title)
    print("%d %d %s %s" %(x, y, button, pressed))
    if (button == Button.right):
      return False
    if (pressed == True):
      recode.append([title, rx, ry, x, y, "down"])
    else:
      index = check_down(recode)
      print("change ", recode[index][5], index, recode[index][3], recode[index][4])
      
      unuse, last_rx, last_ry = _do_stc(recode[index][3], recode[index][4])
      recode[index][0]  = title
      recode[index][1]  = last_rx
      recode[index][2]  = last_ry
      recode.append([title, rx, ry, x, y, "up"])
      

def on_scroll(x, y, dx, dy):
    title, x, y = _do_stc(x, y)
    print("%d %d %d %dd" %(x, y, dx, dy))

def recode_csv(recode):
    wo = open("wml.csv", 'w', encoding="utf-8")
    w_csv = csv.writer(wo)
    w_csv.writerow(["wintitle", "rel-x","rel-y", "x", "y","mouse-action"])
    # for one in recode:
      # print(one)
    w_csv.writerows(recode);
    wo.close()
with Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
    listener.join()


recode_csv(recode)

